package com.ww.springboot.boot.algorithm.leetcode1;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * 描述：
 *
 * @author 🧑 ‍wanwei
 * @since 2022-05-27 17:50
 */
public class CE1711单词距离 {

    public static void main(String[] args) {


    }


    /**
     * 找到两个key的所有位置 找到其中最近的两个坐标
     *
     * @param words
     * @param word1
     * @param word2
     * @return
     */
    public int findClosest(String[] words, String word1, String word2) {
        if (word1.equals(word2)) {
            return 0;
        }
        List<Integer> index1 = new ArrayList<>();
        List<Integer> index2 = new ArrayList<>();
        int i = 0;
        //双指针
        while (words.length - i > i) {
            if (words[i].equals(word1)) {
                index1.add(i);
            } else if (words[words.length - i].equals(word1)) {
                index1.add(words.length - i);
            }
            if (words[i].equals(word2)) {
                index2.add(i);
            } else if (words[words.length - i].equals(word2)) {
                index2.add(words.length - i);
            }
        }

        //找到两个数组中最接近的值
        index1.sort(Comparator.naturalOrder());
        index2.sort(Comparator.naturalOrder());

        if(index1.get(0)>index2.get(0)){
            return getMin(index1,index2);
        }else {
            return getMin(index2,index1);
        }
    }

    /**
     * 找到一个数 在另一个数组中的间隙位置 再计算较小的距离
     *
     * @param index1
     * @param index2
     * @return
     */
    private int getMin(List<Integer> index1, List<Integer> index2) {

        int min = Integer.MAX_VALUE;
        for (int i = 0; i < index1.size(); i++) {
            int index1Num = index1.get(i);
            for (int j = 1; j < index2.size(); j++) {
                int left = index2.get(j - 1);
                int right = index2.get(j);
                //不可能相等
                if (left < index1Num && right > index1Num) {
                    int min1 = (int) (Math.min(Math.pow(index1Num, left), Math.pow(index1Num, right)));
                    min = Math.min(min1, min);
                    if (min == 1) {
                        //1是最小的距离
                        return 1;
                    }
                } else if (left < index1Num && right < index1Num) {
                    //都小 则数组二往右移
                    continue;
                } else if (left > index1Num && right > index1Num) {
                    //都大 则数组二往右移
                    break;
                }

            }
        }
        return min;
    }

}
